package com.api.shopapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.api.shopapi.entity.*;
import com.api.shopapi.entity.dto.*;
import com.api.shopapi.service.*;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 指挥中心
 * */


@RestController
@RequestMapping("CommandCenter")
public class CommandCenterController extends BaseController {


    @Autowired
    @Qualifier("CommandCenterServiceImplOne")
    private CommandCenterService commandCenterService;

    @Autowired
    @Qualifier("CommandCenterStaffRelServiceImplOne")
    private CommandCenterStaffRelService commandCenterStaffRelService;

    @Autowired
    @Qualifier("UserServiceImplOne")
    private UserService userService;


    @Autowired
    @Qualifier("StaffServiceImplOne")
    private StaffService staffService;


    //添加
    @RequestMapping(value = "Add",method = RequestMethod.POST)
    @Transactional
    public MyResult Add(@RequestBody JSONObject jsonObject) {

        try{
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            String loginName = jsonObject.getString("loginName").trim();
            String phone = jsonObject.getString("phone").trim();
            String password = jsonObject.getString("password");
            String name = jsonObject.getString("name").trim();
            String address = jsonObject.getString("address").trim();


            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/CommandCenter/Add");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);


            User user = userService.getByLoginName(loginName);
            if(user != null){
                return failed("登录名已注册");
            }


            user = new User();
            user.setUserCode(UUID.randomUUID().toString());
            user.setPhone(phone);
            user.setLoginName(loginName);
            user.setPassword(getMD5Str(password));
            user.setName(name);
            user.setCreateTime(new Date());
            user.setUserType(23);
            user.setStatus(1);
            user.setGovernmentCode(staff.getGovernmentCode());
            userService.insert(user);


            CommandCenter commandCenter = new CommandCenter();
            commandCenter.setCommandCenterCode(UUID.randomUUID().toString());
            commandCenter.setUserCode(user.getUserCode());
            commandCenter.setAddress(address);
            commandCenter.setCreateTime(new Date());
            commandCenter.setGovernmentCode(staff.getGovernmentCode());
            commandCenterService.insert(commandCenter);


            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);
        }catch (Exception e){
            insertErrorForAffair("/CommandCenter/Add!",jsonObject,e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return anomalous(getExceptionMsg(e));
        }

    }


    //编辑
    @RequestMapping(value = "Edit",method = RequestMethod.POST)
    @Transactional
    public MyResult Edit(@RequestBody JSONObject jsonObject) {

        try{
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            String loginName = jsonObject.getString("loginName");
            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");
            String address = jsonObject.getString("address");
            int status = jsonObject.getInteger("status");
            String commandCenterCode = jsonObject.getString("commandCenterCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/CommandCenter/Edit");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            CommandCenter commandCenter = commandCenterService.getByCommandCenterCode(commandCenterCode);
            if(commandCenter == null){
                return failed("账号不存在");
            }

            User user2 = userService.getByLoginName(loginName);
            if(user2 != null){
                if(!user2.getUserCode().equals(commandCenter.getUserCode())){
                    return failed("登录名已注册");
                }
            }


            User user = userService.getByUserCode(commandCenter.getUserCode());
            if(user == null){
                return failed("用户不存在");
            }

            commandCenter.setAddress(address);
            commandCenterService.update(commandCenter);

            user.setLoginName(loginName);
            user.setName(name);
            user.setPhone(phone);
            user.setStatus(status);
            userService.update(user);

            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);
        }catch (Exception e){
            insertErrorForAffair("/CommandCenter/Edit!",jsonObject,e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return anomalous(getExceptionMsg(e));
        }

    }

    //政府下的指挥中心列表
    @RequestMapping(value = "List",method = RequestMethod.POST)
    public MyResult List(@RequestBody JSONObject jsonObject) {

        try{
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            String governmentCode = jsonObject.getString("governmentCode");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/CommandCenter/List");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            List<CommandCenter> list = commandCenterService.listByGovernmentCode(governmentCode,1);

            List<CommendCenterDTO> listDTO = new ArrayList<>();
            for(CommandCenter commandCenter:list){
                commandCenter = commandCenterService.getByCommandCenterCode(commandCenter.getCommandCenterCode());
                CommendCenterDTO dto = mapper.map(commandCenter,CommendCenterDTO.class);

                User user = userService.getByUserCode(commandCenter.getUserCode());
                dto.setLoginName(user.getLoginName());
                dto.setName(user.getName());
                dto.setPhone(user.getPhone());
                dto.setStatus(user.getStatus());

                listDTO.add(dto);
            }

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("list",listDTO);

            return success(jsonObject1);
        }catch (Exception e){
            insertError("/CommandCenter/List",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }

    //翻页列表
    @RequestMapping(value = "Page",method = RequestMethod.POST)
    public MyResult Page(@RequestBody JSONObject jsonObject) {

        try{
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            int status = jsonObject.getInteger("status");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign,staffCode,"/CommandCenter/Page");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);

            PageInfo<CommandCenter> pageInfo = commandCenterService.PageByGovernmentCode(pageIndex,
                    pageSize, staff.getGovernmentCode(),status);

            List<CommendCenterDTO> listDTO = new ArrayList<>();
            for(CommandCenter commandCenter:pageInfo.getList()){
                commandCenter = commandCenterService.getByCommandCenterCode(commandCenter.getCommandCenterCode());
                CommendCenterDTO dto = mapper.map(commandCenter,CommendCenterDTO.class);

                User user = userService.getByUserCode(commandCenter.getUserCode());
                dto.setLoginName(user.getLoginName());
                dto.setName(user.getName());
                dto.setPhone(user.getPhone());
                dto.setStatus(user.getStatus());



                List<CommandCenterStaffRel> listCommandCenterStaffRel =
                        commandCenterStaffRelService.ListByCommandCenterCode(commandCenter.getCommandCenterCode());
                List<CommandCenterStaffRelDTO> listCommandCenterStaffRelDTO= new ArrayList<>();
                for(CommandCenterStaffRel commandCenterStaffRel:listCommandCenterStaffRel){

                    CommandCenterStaffRelDTO commandCenterStaffRelDTO = mapper.map(commandCenterStaffRel,CommandCenterStaffRelDTO.class);

                    CommandCenter commandCenter1 = commandCenterService.getByCommandCenterCode(commandCenterStaffRelDTO.getCommandCenterCode());
                    User user2 = userService.getByUserCode(commandCenter1.getUserCode());
                    commandCenterStaffRelDTO.setCommandCenterName(user2.getName());

                    Staff staff1 = staffService.getByStaffCode(commandCenterStaffRelDTO.getStaffCode());
                    commandCenterStaffRelDTO.setStaffName(staff1.getLoginName());

                    listCommandCenterStaffRelDTO.add(commandCenterStaffRelDTO);
                }
                dto.setListCommandCenterStaffRelDTO(listCommandCenterStaffRelDTO);

                listDTO.add(dto);

            }

            PageInfo<CommendCenterDTO> pageInfo1 = new PageInfo<>();
            pageInfo1.setList(listDTO);
            pageInfo1.setTotal(pageInfo.getTotal());

            return success(pageInfo1);
        }catch (Exception e){
            insertError("/CommandCenter/Page",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }

    //登录
    @RequestMapping(value = "Login",method = RequestMethod.POST)
    public MyResult Login(@RequestBody JSONObject jsonObject) {

        try{
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            String loginName = jsonObject.getString("loginName").trim();
            String password = jsonObject.getString("password");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/CommandCenter/Login");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            User user = userService.getByLoginNameAndPassword(loginName,getMD5Str(password));
            if(user == null){
                return failed("用户名或者密码错误");
            }
            if(user.getStatus() == 2){
                return failed("账户被禁用");
            }
            if(user.getUserType() != 23){
                return failed("账户类型错误");
            }


            CommandCenter commandCenter = commandCenterService.getByUserCode(user.getUserCode());


            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("user",user);
            jsonObject1.put("commandCenter",commandCenter);

            return success(jsonObject1);
        }catch (Exception e){
            insertError("/CommandCenter/Login",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }

    }




}
